import store from '@/store/index.js'
import {
	HTTP_REQUEST_URL,
	HEADER
} from '@/config/app.js'
import Request from '@/uni_modules/uview-ui/libs/luch-request/index.js'

import silenceAuthHandle from "@/libs/silenceAuth.js"

// 重试请求队列
let requests = [];
let main = false;
const http = new Request()

http.setConfig((config) => {
	/* 设置全局配置 */
	config.baseURL = HTTP_REQUEST_URL /* 根域名不同 */
	config.header = {
		...HEADER,
	}

	return config
})
http.interceptors.request.use(async (config) => {
	/* 请求拦截器。可以使用async await 做异步操作 */
	if(config.custom.auth){
		let token =await silenceAuthHandle()//静默授权
		config.header['api-token'] =token
	}
	
	if (config.custom && config.custom.loading) {
		main = true;
		uni.showLoading({
			title: config.custom.loadText || '加载中'
		});
	}

	return config

}, (config) => {
	return Promise.reject(config)
})
http.interceptors.response.use(async (response) => {
	/* 响应拦截器。可以使用async await 做异步操作  */
	const res = response.data
	uni.hideLoading();

	if (res.code != 1) { // 服务端返回的状态码不等于200，则reject()
		uni.showToast({
			title: res.info,
			icon: 'none'
		});
		if (res.code == 401) {
			// 登录过期处理
			console.log(11111111);
			store.commit('LOGOUT')
			uni.navigateTo({
				url: '/pages/auth/mplogin'
			})
			return Promise.reject(res.info)
		}
		return Promise.reject(res.info)
	}

	return Promise.resolve(res)
}, (err) => { // 请求错误做点什么。可以使用async await 做异步操作
	console.log(err, "请求错误");
	const status = err.response.data
	if (main) {
		uni.hideLoading();
		main = false;
	}

	return Promise.reject(response)
})

export {
	http
}